// Time Tracker by Eric Nadeau (nado18@gmail.com)
// Copyright (C) 2007 by Eric Nadeau
// Distributed under the terms of the GNU General Public License (see GPL.txt)

package view;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

import model.*;

/**
 * @author Eric Nadeau (nado18@gmail.com), on Apr 21, 2004
 */
public class MainWindow extends JFrame {
	private static final String SAVE_FILE = "Time Tracker.projects";
	private ProjectTableModel ptm = new ProjectTableModel();
	private MainPanel list = new MainPanel(this, ptm);
	
	public MainWindow() {
		super("Time Tracker");
		
		try {
			setIconImage( new ImageIcon(Object.class.getResource("/Timer.gif")).getImage() );
		}
		catch(Exception ex) {}
		
		setContentPane(list);
		
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent ev) {
				quit();
			}
		});
		
		listenToMacEvents();
		
		int W = 400;
		int H = 260;
		this.setSize(W, H);
		
		Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation( (ss.width-W)/2, (ss.height-H)/2 );
		
		try {
			ptm.loadProjectsFromFile(SAVE_FILE);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		
		setVisible(true);
		list.updateColumnWidths();
	}
	
	private void quit() {
		try {
			ptm.saveProjectsToFile(SAVE_FILE);
		}
		catch (IOException ex) {
			ex.printStackTrace();
		}
		
		System.exit(0);
	}
	
	public void update() {
		list.update(ptm.getBill());
	}

	private void listenToMacEvents() {
		if( System.getProperty("os.name").toLowerCase().startsWith("mac") ) {
			new MacintoshListener(new Runnable() {
				public void run() {
					quit();
				}
			});
		}
	}

}
